package com.itheima.pinda.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.pinda.DTO.truck.TruckDto;
import com.itheima.pinda.common.CustomIdGenerator;
import com.itheima.pinda.common.utils.Constant;
import com.itheima.pinda.entity.PdTruck;
import com.itheima.pinda.mapper.PdTruckMapper;
import com.itheima.pinda.service.PdTruckService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class PdTruckServiceImpl implements PdTruckService {

    @Autowired
    private CustomIdGenerator idGenerator;
    @Autowired
    private PdTruckMapper truckMapper;


    @Override
    @Transactional
    public TruckDto truckInsert(TruckDto truckDto) {

        PdTruck pdTruck = new PdTruck();
        BeanUtils.copyProperties(truckDto,pdTruck);

        if (StringUtils.isEmpty(pdTruck.getId())){
            // 新增
            pdTruck.setId(idGenerator.nextId(pdTruck) + "");
            truckMapper.insert(pdTruck);
            truckDto.setId(pdTruck.getId());
        }else {
            // 修改
            truckMapper.updateById(pdTruck);
        }
        return truckDto;
    }

    @Override
    public TruckDto truckSelectById(String id) {
        PdTruck pdTruck = truckMapper.selectById(id);
        TruckDto truckDto = new TruckDto();
        BeanUtils.copyProperties(pdTruck,truckDto);
        return truckDto;
    }

    @Override
    public IPage truckByPage(Integer pageNum, Integer pageSize, String truckTypeId, String licensePlate, String fleetId) {

        Page<PdTruck> truckPage = new Page<>(pageNum, pageSize);
        Page<PdTruck> page = truckMapper.selectPage(truckPage, new LambdaQueryWrapper<PdTruck>()
                .eq(PdTruck::getTruckTypeId, truckTypeId)
                .eq(PdTruck::getLicensePlate, licensePlate)
                .eq(PdTruck::getFleetId, fleetId));


        ArrayList<TruckDto> truckDtos = new ArrayList<>();
        List<PdTruck> records = page.getRecords();
        for (PdTruck pdTruck : records) {
            TruckDto truckDto = new TruckDto();
            BeanUtils.copyProperties(pdTruck,truckDto);
            truckDtos.add(truckDto);
        }

        return new Page<TruckDto>().setRecords(truckDtos);
    }

    @Override
    public void truckDelete(List<String> ids) {
        truckMapper.update(null,
                new LambdaUpdateWrapper<PdTruck>()
                        .set(PdTruck::getStatus, Constant.DATA_DISABLE_STATUS)
                        .in(PdTruck::getId,ids));
    }
}
